package com.lee.common.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

public class Common {
	// 默认除法运算精度
	private static final int DEF_DIV_SCALE = 10;

	/**
	 * String转换double
	 * 
	 * @param string
	 * @return double
	 */
	public static double convertSourData(String dataStr) throws Exception {
		if (dataStr != null && !"".equals(dataStr)) {
			return Double.valueOf(dataStr);
		}
		throw new NumberFormatException("convert error!");
	}

	/**
	 * 判断变量是否为空
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isEmpty(String s) {
		if (null == s || "".equals(s) || "".equals(s.trim()) || "null".equalsIgnoreCase(s)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 使用率计算
	 * 
	 * @return
	 */
	public static String fromUsage(long free, long total) {
		Double d = new BigDecimal(free * 100 / total).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
		return String.valueOf(d);
	}

	/**
	 * 返回当前时间　格式：yyyy-MM-dd hh:mm:ss
	 * 24小时制（HH）12小时（hh）
	 * @return String
	 */
	public static String fromDateH() {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format1.format(new Date());
	}

	/**
	 * 返回当前时间　格式：yyyy-MM-dd hh:mm:ss
	 * 
	 * @return String
	 */
	public static String fromDateM() {
		DateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmss");
		return format1.format(new Date());
	}

	/**
	 * 返回当前时间　格式：yyyy-MM-dd
	 * 
	 * @return String
	 */
	public static String fromDateY() {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		return format1.format(new Date());
	}

	/**
	 * 返回近5年年度
	 * 
	 * @return
	 */
	public static List<String> fromDateYears() {
		List<String> years = new ArrayList<String>();
		DateFormat format1 = new SimpleDateFormat("yyyy");
		int nowYear = Integer.parseInt(format1.format(new Date()));
		for (int i = 0; i < 5; i++) {
			years.add((nowYear + 1 - i) + "");
		}
		return years;
	}

	/**
	 * 返回时间格式yyyy-MM
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static String fromDateYD(String datestr) throws ParseException {
		DateFormat format = new SimpleDateFormat("yyyy-MM");
		Date date = format.parse(datestr);
		return format.format(date);
	}
	/**
	 * 返回时间格式yyyy-MM
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static String fromDateYMD(String datestr) throws ParseException {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = format.parse(datestr);
		return format.format(date);
	}
	/**
	 * 返回时间格式yyyy年MM月
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static String fromDateYM(String datestr) throws ParseException {
		if (!isEmpty(datestr)) {
			DateFormat format = new SimpleDateFormat("yyyy-MM");
			Date date = format.parse(datestr);
			String formatDateStr = format.format(date);
			return formatDateStr.split("-")[0] + "年" + formatDateStr.split("-")[1] + "月";
		}
		return "";
	}

	public static List<String> fromDateYear() {
		List<String> years = new ArrayList<String>();
		DateFormat format1 = new SimpleDateFormat("yyyy");
		int nowYear = Integer.parseInt(format1.format(new Date()));
		for (int i = 0; i < 5; i++) {
			years.add((nowYear - i) + "");
		}
		return years;
	}

	/**
	 * 返回当前年度前五年(算当年)
	 * flag:true--正数12345
	 * false--倒数54321 
	 * b:true--前5年
	 * false--后5年
	 * nowyear--2017<br>
	 *[2013, 2014, 2015, 2016, 2017]truetrue<br>
	 *[2017, 2018, 2019, 2020, 2021]truefalse<br>
	 *[2021, 2020, 2019, 2018, 2017]falsefalse<br>
	 *[2017, 2016, 2015, 2014, 2013]falsetrue<br>
	 * 
	 * @return String
	 */
	public static List<String> fromDateYearsNow(int year,boolean flag,boolean b) {
		List<String> years = new ArrayList<String>();
		DateFormat format1 = new SimpleDateFormat("yyyy");
		int nowYear = Integer.parseInt(format1.format(new Date()));
		if(flag){
			if(b){
				for (int i = year-1; i >= 0; i--) {
					years.add((nowYear - i) + "");
				}
			}else {
				for (int i = 0; i < year; i++) {
					years.add((nowYear + i) + "");
				}
			}
		}else{
			//倒数
			if (b) {//前5年
				for (int i = 0; i < year; i++) {
					years.add((nowYear - i) + "");
				}
			}else {
				nowYear = nowYear + year-1;
				for (int i = 0; i < year; i++) {
					years.add((nowYear - i) + "");
				}
			}
		}
		return years;
	}
	/**
	 * 返回当月前五月(算当月)
	 * flag:true--正数12345
	 * false--倒数54321 
	 * b:true--前5天
	 * false--后5天<br>
	 * [2016-09, 2016-10, 2016-11, 2016-12, 2017-01]truetrue
	 * [2017-01, 2017-02, 2017-03, 2017-04, 2017-05]truefalse
	 * [2017-05, 2017-04, 2017-03, 2017-02, 2017-01]falsefalse
	 * [2017-01, 2016-12, 2016-11, 2016-10, 2016-09]falsetrue
	 * 
	 * @return String
	 */
	public static List<String> fromDateMonthNow(int month,boolean flag,boolean b) {
		List<String> months = new ArrayList<String>();
		Calendar calendar = Calendar.getInstance();
		Date date=new Date();  //取当前时间(17)
		calendar.setTime(date);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
		String dateString = formatter.format(date);
		//正数
		if(flag){
			//前几天(13,14,15,16,17)true,true
			if(b){
				//获取前day天，设置为calendar
				int nowMonth = calendar.get(Calendar.MONTH);
				calendar.set(Calendar.MONTH, nowMonth-month+1);
				Date nowDate = calendar.getTime();
				dateString = formatter.format(nowDate);
			}
			//后几天(17,18,19,20,21)true,false
			months.add(dateString);//当天
			for (int i = 0; i < month-1; i++) {
				calendar.add(Calendar.MONTH, 1);
				date=calendar.getTime(); 
				dateString = formatter.format(date);
				months.add(dateString);
			}
		}else{
			//倒数
			//前几天（17,16,15,14,13）fasle,false
			if(!b){
				int nowDay = calendar.get(Calendar.MONTH);
				calendar.set(Calendar.MONTH, nowDay+month-1);
				Date nowDate = calendar.getTime();
				dateString = formatter.format(nowDate);
			}
			months.add(dateString);
			//后几天（21,20,19,18,17）false,true
			for (int i = 0; i < month-1; i++) {
				calendar.add(Calendar.MONTH, -1);
				date=calendar.getTime(); 
				dateString = formatter.format(date);
				months.add(dateString);
			}
		}
		return months;
	}
	/**
	 * 返回当天前后五天(算当天)
	 * flag:true--正数12345
	 * false--倒数54321
	 * b:true--前5天
	 * false--后5天<br>
	 * date--17<br>
	 * (13,14,15,16,17)true,true<br>
	 * (17,18,19,20,21)true,false<br>
	 * (21,20,19,18,17)false,false<br>
	 * (17,16,15,14,13)fasle,true
	 * @return String
	 */
	public static List<String> fromDateDayNow(int day,boolean flag,boolean b) {
		List<String> days = new ArrayList<String>();
		Calendar calendar = Calendar.getInstance();
		Date date=new Date();  //取当前时间(17)
		calendar.setTime(date);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(date);
		//正数
		if(flag){
			//前几天(13,14,15,16,17)true,true
			if(b){
				//获取前day天，设置为calendar
				int nowDay = calendar.get(Calendar.DATE);
				calendar.set(Calendar.DATE, nowDay-day+1);
				Date nowDate = calendar.getTime();
				dateString = formatter.format(nowDate);
			}
			//后几天(17,18,19,20,21)true,false
			days.add(dateString);//当天
			for (int i = 0; i < day-1; i++) {
				calendar.add(Calendar.DAY_OF_MONTH, 1);
				date=calendar.getTime(); 
				dateString = formatter.format(date);
				days.add(dateString);
			}
		}else{
			//倒数
			//前几天（17,16,15,14,13）fasle,false
			if(!b){
				int nowDay = calendar.get(Calendar.DATE);
				calendar.set(Calendar.DATE, nowDay+day-1);
				Date nowDate = calendar.getTime();
				dateString = formatter.format(nowDate);
			}
			days.add(dateString);
			//后几天（21,20,19,18,17）false,true
			for (int i = 0; i < day-1; i++) {
				calendar.add(Calendar.DAY_OF_MONTH, -1);
				date=calendar.getTime(); 
				dateString = formatter.format(date);
				days.add(dateString);
			}
		}
		return days;
	}

	/**
	 * 用来去掉List中空值和相同项的。
	 * 
	 * @param list
	 * @return
	 */
	public static List<String> removeSameItem(List<String> list) {
		List<String> difList = new ArrayList<String>();
		for (String t : list) {
			if (t != null && !difList.contains(t)) {
				difList.add(t);
			}
		}
		return difList;
	}

	/**
	 * 返回用户的IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String toIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 传入原图名称，，获得一个以时间格式的新名称
	 * 
	 * @param fileName
	 *            　原图名称
	 * @return
	 */
	public static String generateFileName(String fileName) {
		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		String formatDate = format.format(new Date());
		int random = new Random().nextInt(10000);
		int position = fileName.lastIndexOf(".");
		String extension = fileName.substring(position);
		return formatDate + random + extension;
	}

	/**
	 * 取得html网页内容 UTF8编码
	 * 
	 * @param urlStr
	 *            网络地址
	 * @return String
	 */
	public static String getInputHtmlUTF8(String urlStr) {
		URL url = null;
		try {
			url = new URL(urlStr);
			HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection();

			httpsURLConnection.setRequestMethod("GET");
			httpsURLConnection.setConnectTimeout(5 * 1000);
			httpsURLConnection.connect();
			if (httpsURLConnection.getResponseCode() == 200) {
				// 通过输入流获取网络图片
				InputStream inputStream = httpsURLConnection.getInputStream();
				String data = readHtml(inputStream, "UTF-8");
				inputStream.close();
				return data;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return null;

	}

	/**
	 * 取得html网页内容 GBK编码
	 * 
	 * @param urlStr
	 *            网络地址
	 * @return String
	 */
	public static String getInputHtmlGBK(String urlStr) {
		URL url = null;
		try {
			url = new URL(urlStr);
			HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection();

			httpsURLConnection.setRequestMethod("GET");
			httpsURLConnection.setConnectTimeout(5 * 1000);
			httpsURLConnection.connect();
			if (httpsURLConnection.getResponseCode() == 200) {
				// 通过输入流获取网络图片
				InputStream inputStream = httpsURLConnection.getInputStream();
				String data = readHtml(inputStream, "GBK");
				inputStream.close();
				return data;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return null;

	}

	/**
	 * @param inputStream
	 * @param uncode
	 *            编码 GBK 或 UTF-8
	 * @return
	 * @throws Exception
	 */
	public static String readHtml(InputStream inputStream, String uncode) throws Exception {
		InputStreamReader input = new InputStreamReader(inputStream, uncode);
		BufferedReader bufReader = new BufferedReader(input);
		String line = "";
		StringBuilder contentBuf = new StringBuilder();
		while ((line = bufReader.readLine()) != null) {
			contentBuf.append(line);
		}
		return contentBuf.toString();
	}

	/**
	 * 
	 * @return 返回资源的二进制数据 @
	 */
	public static byte[] readInputStream(InputStream inputStream) {

		// 定义一个输出流向内存输出数据
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		// 定义一个缓冲区
		byte[] buffer = new byte[1024];
		// 读取数据长度
		int len = 0;
		// 当取得完数据后会返回一个-1
		try {
			while ((len = inputStream.read(buffer)) != -1) {
				// 把缓冲区的数据 写到输出流里面
				byteArrayOutputStream.write(buffer, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				byteArrayOutputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}

		// 得到数据后返回
		return byteArrayOutputStream.toByteArray();

	}

	/**
	 * 获取当前认证通过的用户名
	 * 
	 * @return
	 */
	/*public static String findAuthenticatedUsername() {
		String username = null;
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (principal instanceof UserDetails) {
			username = ((UserDetails) principal).getUsername();
		} else {
			username = principal.toString();
		}
		return username;
	}*/

	/**
	 * 获取登录账号的ID
	 * 
	 * @author lanyuan Email：mmm333zzz520@163.com date：2014-2-27
	 * @param request
	 * @return
	 */
	public static String findUserSessionId(HttpServletRequest request) {
		return request.getSession().getAttribute("userSessionId").toString();
	}

	/**
	 * 获取登录账号的的对象
	 * 
	 * @author lanyuan Email：mmm333zzz520@163.com date：2014-2-27
	 * @param request
	 * @return Object 返回是Object..需要转型为(Account)Object
	 */
	public static Object findUserSession(HttpServletRequest request) {
		return (Object) request.getSession().getAttribute("userSession");
	}

	/**
	 * 提供精确的减法运算。
	 * 
	 * @param v1
	 *            被减数
	 * @param v2
	 *            减数
	 * @return 两个参数的差
	 */
	public static double sub(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.subtract(b2).doubleValue();
	}

	/**
	 * 提供精确的加法运算。
	 * 
	 * @param v1
	 *            被加数
	 * @param v2
	 *            加数
	 * @return 两个参数的和
	 */
	public static double add(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.add(b2).doubleValue();
	}

	/**
	 * 提供精确的乘法运算。
	 * 
	 * @param v1
	 *            被乘数
	 * @param v2
	 *            乘数
	 * @return 两个参数的积
	 */
	public static double mul(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.multiply(b2).doubleValue();
	}

	/**
	 * 提供（相对）精确的除法运算，当发生除不尽的情况时，精确到 小数点以后10位，以后的数字四舍五入。
	 * 
	 * @param v1
	 *            被除数
	 * @param v2
	 *            除数
	 * @return 两个参数的商
	 */
	public static double div(double v1, double v2) {
		return div(v1, v2, DEF_DIV_SCALE);
	}

	/**
	 * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指 定精度，以后的数字四舍五入。
	 * 
	 * @param v1
	 *            被除数
	 * @param v2
	 *            除数
	 * @param scale
	 *            表示表示需要精确到小数点以后几位。
	 * @return 两个参数的商
	 */
	public static double div(double v1, double v2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	/**
	 * 将Map形式的键值对中的值转换为泛型形参给出的类中的属性值 t一般代表pojo类
	 * 
	 * @descript
	 * @param t
	 * @param params
	 * @author lanyuan
	 * @date 2015年3月29日
	 * @version 1.0
	 */
	public static <T extends Object> T flushObject(T t, Map<String, Object> params) {
		if (params == null || t == null)
			return t;

		Class<?> clazz = t.getClass();
		for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
			try {
				Field[] fields = clazz.getDeclaredFields();

				for (int i = 0; i < fields.length; i++) {
					String name = fields[i].getName(); // 获取属性的名字
					Object value = params.get(name);
					if (value != null && !"".equals(value)) {
						// 注意下面这句，不设置true的话，不能修改private类型变量的值
						fields[i].setAccessible(true);
						fields[i].set(t, value);
					}
				}
			} catch (Exception e) {
			}

		}
		return t;
	}

	/**
	 * html转议
	 * 
	 * @descript
	 * @param content
	 * @return
	 * @author LJN
	 * @date 2015年4月27日
	 * @version 1.0
	 */
	public static String stringtohtml(String content) {
		if (content == null)
			return "";
		String html = content;
		html = html.replace("&apos;", "'");
		html = html.replaceAll("&amp;", "&");
		html = html.replace("&quot;", "\""); // "
		html = html.replace("&nbsp;&nbsp;", "\t");// 替换跳格
		html = html.replace("&nbsp;", " ");// 替换空格
		html = html.replace("&lt;", "<");
		html = html.replaceAll("&gt;", ">");

		return html;
	}
	/**
	 * 
	 * strimAll:去除字符串所有空格. <br/>
	 * TODO(这里描述这个方法适用条件 – 可选).<br/>
	 * TODO(这里描述这个方法的执行流程 – 可选).<br/>
	 * TODO(这里描述这个方法的使用方法 – 可选).<br/>
	 * TODO(这里描述这个方法的注意事项 – 可选).<br/>
	 *
	 * @author dell
	 * @param str
	 * @return
	 * @since JDK 1.7
	 */
	public static String strimAll(String str){
		return str.replace(" ", "");
	}
	
	public static void main(String[] args) {
		List<String> lsList1 = fromDateYearsNow(5, true,true);
		List<String> lsList2 = fromDateYearsNow(5, true,false);
		List<String> lsList3 = fromDateYearsNow(5, false,true);
		List<String> lsList4 = fromDateYearsNow(5, false,false);
		System.out.println(lsList1+"true"+"true");
		System.out.println(lsList2+"true"+"false");
		System.out.println(lsList4+"false"+"false");
		System.out.println(lsList3+"false"+"true");
	}
}
